﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;

namespace 华视身份证读卡器测试
{
    public class ReadCardHelper
    {



        private bool Init()
        {
            CVRSDK.CVR_CloseComm();
            int iRetUSB = 0;
            int iPort;
            for (iPort = 1001; iPort <= 1016; iPort++)
            {
                iRetUSB = CVRSDK.CVR_InitComm(iPort);
                if (iRetUSB == 1)
                {
                    break;
                }
            }
            return iRetUSB == 1;
        }

        public SfzModel ReadCard()
        {
            var init = Init();
            if (!init)
            {
                throw new Exception("初始化失败");
            }

            int authenticate = CVRSDK.CVR_Authenticate();
            if (authenticate == 1)
            {
                int readContent = CVRSDK.CVR_Read_Content(4);
                if (readContent == 1)
                {
                   var sfz = FillData(); 
                    return sfz;
                }
                else
                {
                    Console.WriteLine("读卡操作失败！需要拿开再放置！");
                }
            }
            return null;
        }

        private SfzModel FillData()
        {

            //pictureBox1.ImageLocation = Application.StartupPath + "\\zp.bmp";
            byte[] name = new byte[30];
            int length = 30;
            CVRSDK.GetPeopleName(ref name[0], ref length);
            byte[] number = new byte[30];
            length = 36;
            CVRSDK.GetPeopleIDCode(ref number[0], ref length);
            byte[] people = new byte[30];
            length = 3;
            CVRSDK.GetPeopleNation(ref people[0], ref length);
            byte[] validtermOfStart = new byte[30];
            length = 16;
            CVRSDK.GetStartDate(ref validtermOfStart[0], ref length);
            byte[] birthday = new byte[30];
            length = 16;
            CVRSDK.GetPeopleBirthday(ref birthday[0], ref length);
            byte[] address = new byte[30];
            length = 70;
            CVRSDK.GetPeopleAddress(ref address[0], ref length);
            byte[] validtermOfEnd = new byte[30];
            length = 16;
            CVRSDK.GetEndDate(ref validtermOfEnd[0], ref length);
            byte[] signdate = new byte[30];
            length = 30;
            CVRSDK.GetDepartment(ref signdate[0], ref length);
            byte[] sex = new byte[30];
            length = 3;
            CVRSDK.GetPeopleSex(ref sex[0], ref length);

            byte[] samid = new byte[32];
            CVRSDK.CVR_GetSAMID(ref samid[0]);

            string photo = "";
            var imagePath = $"{System.AppDomain.CurrentDomain.BaseDirectory}\\zp.bmp";
            using (Bitmap bmp = new Bitmap(imagePath))
            {
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                photo = Convert.ToBase64String(arr);
            }
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            var Address = System.Text.Encoding.GetEncoding("GB2312").GetString(address).Replace("\0", "").Trim();
            var Sex = System.Text.Encoding.GetEncoding("GB2312").GetString(sex).Replace("\0", "").Trim();
            var Birthday = System.Text.Encoding.GetEncoding("GB2312").GetString(birthday).Replace("\0", "").Trim();
            var Dept = System.Text.Encoding.GetEncoding("GB2312").GetString(signdate).Replace("\0", "").Trim();
            var IdCard = System.Text.Encoding.GetEncoding("GB2312").GetString(number).Replace("\0", "").Trim();
            var Name = System.Text.Encoding.GetEncoding("GB2312").GetString(name).Replace("\0", "").Trim();
            var Nation = System.Text.Encoding.GetEncoding("GB2312").GetString(people).Replace("\0", "").Trim();
            var ValidDate = System.Text.Encoding.GetEncoding("GB2312").GetString(validtermOfStart).Replace("\0", "").Trim() + "-" + System.Text.Encoding.GetEncoding("GB2312").GetString(validtermOfEnd).Replace("\0", "").Trim();


            //Console.WriteLine("姓名：" + Name);
            //Console.WriteLine("性别：" + Sex);
            //Console.WriteLine("民族：" + Nation);
            //Console.WriteLine("出生日期：" + Birthday);
            //Console.WriteLine("地址：" + Address);
            //Console.WriteLine("身份证号：" + IdCard);
            //Console.WriteLine("签发机关：" + Dept);
            //Console.WriteLine("有效期：" + ValidDate);
            //Console.WriteLine("照片：" + photo);


            return new SfzModel()
            {
                Name = Name,
                Nation = Nation,
                Sex = Sex,
                Birthday = Birthday,
                Address = Address,
                Photo = photo,
                IdCard = IdCard,
                Dept = Dept,
                ValidDate = ValidDate,
            };
        }

        /// <summary>
        /// 身份证信息
        /// </summary>
        public class SfzModel
        {
            /// <summary>
            /// 姓名
            /// </summary>
            public string Name;     //姓名
            /// <summary>
            /// 性别
            /// </summary>
            public String Sex;      //性别
            /// <summary>
            /// 民族
            /// </summary>
            public String Nation;    //民族，护照识别时此项为空
            /// <summary>
            /// 出生日期
            /// </summary>
            public String Birthday;   //出生日期
            /// <summary>
            /// 地址
            /// </summary>
            public String Address;  //地址，在识别护照时导出的是国籍简码
            /// <summary>
            /// 身份证号码
            /// </summary>
            public string IdCard;  //地址，在识别护照时导出的是国籍简码 
            /// <summary>
            /// 有效起始日期
            /// </summary>
            public string ValidDate;  //有效起始日期，在识别护照时为空 
            /// <summary>
            /// 照片
            /// </summary>
            public string Photo;
            /// <summary>
            /// 签发机关
            /// </summary>
            public string Dept;

            public override string ToString()
            {
                 return $"姓名：{Name}，性别：{Sex}，民族：{Nation}，出生日期：{Birthday}，地址：{Address}，身份证号：{IdCard}，签发机关：{Dept}，有效期：{ValidDate}";
            }
        }
    }
}
